import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
import '../../widgets/platform/adaptive_card.dart';
import '../../widgets/database/table_schema_widget.dart';
import '../../../data/services/data_management_service.dart';

/// 智能电子表格页面
/// 提供类似NocoDB的电子表格界面，支持数据库表的查看和编辑
class SpreadsheetPage extends ConsumerStatefulWidget {
  final String tableName;
  final int projectId;
  final Map<String, dynamic>? connectionConfig;

  const SpreadsheetPage({
    super.key,
    required this.tableName,
    required this.projectId,
    this.connectionConfig,
  });

  @override
  ConsumerState<SpreadsheetPage> createState() => _SpreadsheetPageState();
}

class _SpreadsheetPageState extends ConsumerState<SpreadsheetPage> {
  List<Map<String, dynamic>> _tableData = [];
  List<String> _columnNames = [];
  List<Map<String, dynamic>> _originalData = [];
  bool _isLoading = false;
  bool _isOffline = false;
  bool _isConnectedToDB = false;
  String? _error;
  final TextEditingController _searchController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _checkConnectivity();
    _isConnectedToDB = widget.connectionConfig != null;
    _loadTableData();
  }

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }

  /// 检查网络连接状态
  Future<void> _checkConnectivity() async {
    // 在实际应用中，这里应该检查真实的网络状态
    // 目前我们模拟离线状态
    setState(() {
      _isOffline = false; // 默认在线
    });
  }

  /// 加载表格数据
  Future<void> _loadTableData() async {
    setState(() {
      _isLoading = true;
      _error = null;
    });

    try {
      if (_isOffline) {
        // 离线模式：从本地存储加载数据
        await _loadDataFromLocalStorage();
      } else {
        // 在线模式：从服务器加载数据
        await _loadDataFromServer();
      }

      setState(() {
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _error = '加载数据失败: ${e.toString()}';
        _isLoading = false;
      });
    }
  }

  /// 从服务器加载数据
  Future<void> _loadDataFromServer() async {
    if (_isConnectedToDB && widget.connectionConfig != null) {
      // 从数据库加载数据
      await _loadDataFromDatabase();
    } else {
      // TODO: 调用实际的API获取表格数据
      // 模拟数据加载
      await Future.delayed(const Duration(seconds: 1));

      // 模拟表格数据
      _columnNames = ['ID', '任务名称', '描述', '优先级', '负责人', '状态', '截止日期'];
      _tableData = [
        {
          'ID': 1,
          '任务名称': '用户登录功能',
          '描述': '实现用户注册和登录功能',
          '优先级': '高',
          '负责人': '张三',
          '状态': '进行中',
          '截止日期': '2024-03-15',
        },
        {
          'ID': 2,
          '任务名称': 'Excel解析模块',
          '描述': '实现Excel文件上传和解析功能',
          '优先级': '高',
          '负责人': '李四',
          '状态': '已完成',
          '截止日期': '2024-03-10',
        },
        {
          'ID': 3,
          '任务名称': '智能表格界面',
          '描述': '开发类似NocoDB的智能表格界面',
          '优先级': '中',
          '负责人': '王五',
          '状态': '进行中',
          '截止日期': '2024-03-20',
        },
      ];

      // 保存原始数据用于搜索
      _originalData = List.from(_tableData);

      // 保存到本地存储以支持离线访问
      await _saveDataToLocalStorage();
    }
  }

  /// 从本地存储加载数据
  Future<void> _loadDataFromLocalStorage() async {
    final prefs = await SharedPreferences.getInstance();
    final String? dataString =
        prefs.getString('spreadsheet_${widget.projectId}_${widget.tableName}');

    if (dataString != null) {
      final Map<String, dynamic> data = json.decode(dataString);
      _columnNames = List<String>.from(data['columns']);
      _tableData = List<Map<String, dynamic>>.from(
          data['rows'].map((row) => Map<String, dynamic>.from(row)));
      _originalData = List.from(_tableData);
    } else {
      // 如果没有本地数据，使用默认数据
      _columnNames = ['ID', '任务名称', '描述', '优先级', '负责人', '状态', '截止日期'];
      _tableData = [
        {
          'ID': 1,
          '任务名称': '默认任务',
          '描述': '这是默认任务描述',
          '优先级': '中',
          '负责人': '系统',
          '状态': '待处理',
          '截止日期': '2024-12-31',
        },
      ];
      _originalData = List.from(_tableData);
    }
  }

  /// 保存数据到本地存储
  Future<void> _saveDataToLocalStorage() async {
    final prefs = await SharedPreferences.getInstance();
    final Map<String, dynamic> data = {
      'columns': _columnNames,
      'rows': _tableData,
    };
    final String dataString = json.encode(data);
    await prefs.setString(
        'spreadsheet_${widget.projectId}_${widget.tableName}', dataString);
  }

  /// 同步数据到数据库
  Future<void> _syncDataToDatabase() async {
    // TODO: 实现将数据同步到数据库的逻辑
    // 这里应该根据connectionConfig连接到相应的数据库并更新数据

    // 模拟同步过程
    await Future.delayed(const Duration(seconds: 1));

    // 在实际实现中，这里应该：
    // 1. 比较本地数据和数据库数据的差异
    // 2. 将更改同步到数据库
    // 3. 处理冲突解决
  }

  /// 从数据库加载数据
  Future<void> _loadDataFromDatabase() async {
    try {
      // 使用数据管理服务查询表数据
      final dataManagementService = DataManagementService();
      final tableData = await dataManagementService.queryTableData(
        widget.connectionConfig!,
        widget.tableName,
      );

      // 如果有数据，提取列名
      if (tableData.isNotEmpty) {
        _columnNames = tableData.first.keys.toList();
        _tableData = tableData;
      } else {
        // 如果没有数据，设置默认列名
        final tableSchema = await dataManagementService.getTableSchema(
          widget.connectionConfig!,
          widget.tableName,
        );
        _columnNames = tableSchema
            .map((column) => column['column_name'] as String)
            .toList();
        _tableData = [];
      }

      // 保存原始数据用于搜索
      _originalData = List.from(_tableData);

      // 保存到本地存储以支持离线访问
      await _saveDataToLocalStorage();
    } catch (e) {
      // 如果从数据库加载失败，尝试从本地存储加载
      await _loadDataFromLocalStorage();
      rethrow;
    }
  }

  /// 同步数据到服务器
  Future<void> _syncDataToServer() async {
    if (_isOffline) {
      // 离线时无法同步
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: SelectableText('离线模式下无法同步数据，请联网后重试'),
            backgroundColor: Colors.orange,
          ),
        );
      }
      return;
    }

    try {
      if (_isConnectedToDB && widget.connectionConfig != null) {
        // 同步数据到数据库
        await _syncDataToDatabase();
      } else {
        // TODO: 调用实际的API同步数据到服务器
        await Future.delayed(const Duration(seconds: 1));
      }

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: SelectableText('数据同步成功'),
            backgroundColor: Colors.green,
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: SelectableText('数据同步失败: ${e.toString()}'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('${widget.tableName} - 智能电子表格'),
        backgroundColor: Colors.blue.shade50,
        foregroundColor: Colors.blue.shade700,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Navigator.of(context).pop(),
        ),
        actions: [
          if (_isOffline)
            Container(
              padding: const EdgeInsets.all(8),
              child: const Row(
                children: [
                  Icon(Icons.wifi_off, color: Colors.orange, size: 20),
                  SizedBox(width: 4),
                  Text('离线', style: TextStyle(fontSize: 12)),
                ],
              ),
            ),
          if (_isConnectedToDB)
            Container(
              padding: const EdgeInsets.all(8),
              child: const Row(
                children: [
                  Icon(Icons.link, color: Colors.green, size: 20),
                  SizedBox(width: 4),
                  Text('已连接', style: TextStyle(fontSize: 12)),
                ],
              ),
            ),
          PopupMenuButton<String>(
            onSelected: (value) {
              switch (value) {
                case 'refresh':
                  _loadTableData();
                  break;
                case 'add_row':
                  _addNewRow();
                  break;
                case 'export':
                  _exportData();
                  break;
                case 'schema':
                  _showTableSchema();
                  break;
                case 'sync':
                  _syncDataToServer();
                  break;
                case 'db_connect':
                  _navigateToDbConnection();
                  break;
              }
            },
            itemBuilder: (context) => [
              const PopupMenuItem(
                value: 'refresh',
                child: Row(
                  children: [
                    Icon(Icons.refresh),
                    SizedBox(width: 8),
                    Text('刷新'),
                  ],
                ),
              ),
              const PopupMenuItem(
                value: 'add_row',
                child: Row(
                  children: [
                    Icon(Icons.add),
                    SizedBox(width: 8),
                    Text('添加行'),
                  ],
                ),
              ),
              const PopupMenuItem(
                value: 'export',
                child: Row(
                  children: [
                    Icon(Icons.download),
                    SizedBox(width: 8),
                    Text('导出数据'),
                  ],
                ),
              ),
              if (_isConnectedToDB)
                const PopupMenuItem(
                  value: 'schema',
                  child: Row(
                    children: [
                      Icon(Icons.table_chart),
                      SizedBox(width: 8),
                      Text('表结构'),
                    ],
                  ),
                ),
              if (!_isConnectedToDB)
                const PopupMenuItem(
                  value: 'db_connect',
                  child: Row(
                    children: [
                      Icon(Icons.link),
                      SizedBox(width: 8),
                      Text('连接数据库'),
                    ],
                  ),
                ),
              if (_isConnectedToDB)
                const PopupMenuItem(
                  value: 'sync',
                  child: Row(
                    children: [
                      Icon(Icons.sync),
                      SizedBox(width: 8),
                      Text('同步数据'),
                    ],
                  ),
                ),
            ],
          ),
        ],
      ),
      body: _buildContent(),
    );
  }

  Widget _buildContent() {
    if (_isLoading) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircularProgressIndicator(),
            SizedBox(height: 16),
            Text('正在加载数据...'),
          ],
        ),
      );
    }

    if (_error != null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              Icons.error_outline,
              size: 64,
              color: Colors.red,
            ),
            const SizedBox(height: 16),
            Text(
              _error!,
              style: const TextStyle(color: Colors.red),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: _loadTableData,
              child: const Text('重试'),
            ),
          ],
        ),
      );
    }

    return _buildSpreadsheet();
  }

  Widget _buildSpreadsheet() {
    return SingleChildScrollView(
      child: AdaptiveCard(
        margin: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 表格信息
            _buildTableInfo(),

            const SizedBox(height: 16),

            // 表格工具栏
            _buildToolbar(),

            const SizedBox(height: 16),

            // 表格内容
            _buildTableContent(),
          ],
        ),
      ),
    );
  }

  Widget _buildTableInfo() {
    return Row(
      children: [
        const Icon(Icons.table_chart, color: Colors.blue),
        const SizedBox(width: 8),
        SelectableText(
          widget.tableName,
          style: const TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
          ),
        ),
        const Spacer(),
        SelectableText(
          '${_tableData.length} 行数据',
          style: TextStyle(
            color: Colors.grey.shade600,
            fontSize: 14,
          ),
        ),
      ],
    );
  }

  Widget _buildToolbar() {
    return Row(
      children: [
        ElevatedButton.icon(
          onPressed: _addNewRow,
          icon: const Icon(Icons.add, size: 18),
          label: const SelectableText('添加行'),
        ),
        const SizedBox(width: 8),
        OutlinedButton.icon(
          onPressed: _exportData,
          icon: const Icon(Icons.download, size: 18),
          label: const SelectableText('导出'),
        ),
        const SizedBox(width: 8),
        if (_isOffline)
          OutlinedButton.icon(
            onPressed: _syncDataToServer,
            icon: const Icon(Icons.sync, size: 18),
            label: const SelectableText('同步'),
          ),
        const Spacer(),
        // 搜索框
        SizedBox(
          width: 200,
          child: TextField(
            controller: _searchController,
            decoration: const InputDecoration(
              hintText: '搜索...',
              prefixIcon: Icon(Icons.search, size: 18),
              isDense: true,
              contentPadding: EdgeInsets.symmetric(
                horizontal: 12,
                vertical: 8,
              ),
            ),
            onChanged: _onSearchChanged,
          ),
        ),
      ],
    );
  }

  Widget _buildTableContent() {
    return LayoutBuilder(
      builder: (context, constraints) {
        // 在小屏幕上使用垂直滚动，在大屏幕上使用水平滚动
        if (constraints.maxWidth < 600) {
          // 移动端布局 - 使用卡片形式显示数据
          return _buildMobileTableContent();
        } else {
          // 桌面端布局 - 使用水平滚动的表格
          return _buildDesktopTableContent();
        }
      },
    );
  }

  Widget _buildDesktopTableContent() {
    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: DataTable(
        columns: _columnNames
            .map((name) => DataColumn(
                  label: SelectableText(
                    name,
                    style: const TextStyle(fontWeight: FontWeight.bold),
                  ),
                ))
            .toList(),
        rows: _tableData
            .map((row) => DataRow(
                  cells: _columnNames
                      .map((col) => DataCell(
                            _buildEditableCell(row, col),
                          ))
                      .toList(),
                ))
            .toList(),
      ),
    );
  }

  Widget _buildMobileTableContent() {
    return ListView.builder(
      itemCount: _tableData.length,
      itemBuilder: (context, index) {
        final row = _tableData[index];
        return Card(
          margin: const EdgeInsets.symmetric(vertical: 4, horizontal: 8),
          child: Padding(
            padding: const EdgeInsets.all(12),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                for (final columnName in _columnNames)
                  Padding(
                    padding: const EdgeInsets.only(bottom: 8),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          columnName,
                          style: const TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: 12,
                          ),
                        ),
                        const SizedBox(height: 2),
                        GestureDetector(
                          onTap: () => _editCell(row, columnName),
                          child: Container(
                            padding: const EdgeInsets.all(8),
                            decoration: BoxDecoration(
                              border: Border.all(color: Colors.grey.shade300),
                              borderRadius: BorderRadius.circular(4),
                            ),
                            child: SelectableText(
                              row[columnName]?.toString() ?? '',
                              style: const TextStyle(fontSize: 14),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildEditableCell(Map<String, dynamic> row, String columnName) {
    return GestureDetector(
      onTap: () => _editCell(row, columnName),
      child: Container(
        padding: const EdgeInsets.all(8),
        child: SelectableText(
          row[columnName]?.toString() ?? '',
          style: const TextStyle(fontSize: 14),
        ),
      ),
    );
  }

  void _editCell(Map<String, dynamic> row, String columnName) {
    final TextEditingController controller = TextEditingController(
      text: row[columnName]?.toString() ?? '',
    );

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: SelectableText('编辑 $columnName'),
        content: TextField(
          controller: controller,
          decoration: const InputDecoration(
            border: OutlineInputBorder(),
          ),
          maxLines: 3,
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const SelectableText('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              // 更新数据
              row[columnName] = controller.text;

              // 保存到本地存储
              _saveDataToLocalStorage();

              // 更新UI
              setState(() {});

              Navigator.of(context).pop();

              // 显示提示
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(
                  content: SelectableText('数据已更新'),
                  backgroundColor: Colors.green,
                ),
              );

              // 如果连接到数据库，提示用户需要同步
              if (_isConnectedToDB) {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(
                    content: SelectableText('数据已保存到本地，同步到数据库请使用同步功能'),
                    backgroundColor: Colors.orange,
                  ),
                );
              }
            },
            child: const SelectableText('保存'),
          ),
        ],
      ),
    );
  }

  void _addNewRow() {
    // 创建新行数据
    final Map<String, dynamic> newRow = {};
    for (final column in _columnNames) {
      // 为不同类型的列设置默认值
      if (column.toLowerCase() == 'id') {
        newRow[column] = null; // ID通常由数据库生成
      } else if (column.toLowerCase().contains('time') ||
          column.toLowerCase().contains('date')) {
        newRow[column] = DateTime.now().toString();
      } else {
        newRow[column] = '';
      }
    }

    // 为ID列设置一个临时值（仅用于本地显示）
    if (_columnNames.contains('ID') || _columnNames.contains('id')) {
      final idColumn = _columnNames.contains('ID') ? 'ID' : 'id';
      final maxId = _tableData
          .map((row) => row[idColumn] as int?)
          .where((id) => id != null)
          .fold<int>(0, (max, id) => id! > max ? id : max);
      newRow[idColumn] = maxId + 1;
    }

    setState(() {
      _tableData.add(newRow);
    });

    // 保存到本地存储
    _saveDataToLocalStorage();

    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: SelectableText('已添加新行'),
        backgroundColor: Colors.blue,
      ),
    );

    // 如果连接到数据库，提示用户需要同步
    if (_isConnectedToDB) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: SelectableText('数据已保存到本地，同步到数据库请使用同步功能'),
          backgroundColor: Colors.orange,
        ),
      );
    }
  }

  void _exportData() {
    // TODO: 实现数据导出逻辑
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: SelectableText('数据导出功能开发中...'),
        backgroundColor: Colors.green,
      ),
    );
  }

  void _onSearchChanged(String query) {
    if (query.isEmpty) {
      setState(() {
        _tableData = List.from(_originalData);
      });
    } else {
      setState(() {
        _tableData = _originalData.where((row) {
          return row.values.any((value) {
            return value.toString().toLowerCase().contains(query.toLowerCase());
          });
        }).toList();
      });
    }
  }

  /// 导航到数据库连接页面
  void _navigateToDbConnection() {
    // TODO: 实现导航到数据库连接页面的逻辑
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: SelectableText('数据库连接功能开发中...'),
        backgroundColor: Colors.blue,
      ),
    );
  }

  /// 显示表结构
  void _showTableSchema() {
    if (!_isConnectedToDB || widget.connectionConfig == null) return;

    showModalBottomSheet(
      context: context,
      builder: (context) => TableSchemaWidget(
        connectionConfig: widget.connectionConfig!,
        tableName: widget.tableName,
      ),
      isScrollControlled: true,
    );
  }
}
